from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, UpdateAPIView,RetrieveAPIView,DestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from . import serializers
from .models import User


class CheckUsernameView(APIView):
    def get(self, request, username):
        # 1,根据用户名查询,用户数量
        count = User.objects.filter(username=username).count()

        # 2,返回响应
        data = {
            "count": count
        }
        return Response(data, status=status.HTTP_200_OK)

class CheckMobileView(APIView):
    def get(self, request, mobile):
        # 1,根据用户名查询,用户数量
        count = User.objects.filter(mobile=mobile).count()

        # 2,返回响应
        data = {
            "count": count
        }
        return Response(data, status=status.HTTP_200_OK)

class RegisterUserView(CreateAPIView):
    serializer_class = serializers.RegisterUserSerializer

class EmailSendView(UpdateAPIView):
    serializer_class = serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        return self.request.user

class UserInfoView(RetrieveAPIView):
    serializer_class = serializers.UserInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

class EmailActiveView(APIView):
    def get(self,request):

        token = request.query_params.get('token')

        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user = User.decode_token(token)

        if not user:
            raise Response(status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True

        user.save()

        return Response(status=status.HTTP_200_OK)

class AddressesView(mixins.CreateModelMixin,
                    DestroyAPIView,
                    GenericViewSet,
                    mixins.UpdateModelMixin):
    serializer_class = serializers.AddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self,request):
        queryset = self.get_queryset()

        serializer = self.get_serializer(instance=queryset,many=True)

        return Response({
            "addresses" : serializer.data,
            "limit" : 20,
            "default_address_id" : request.user.default_address_id
        })

    #重写地址的创建方法，是否用户的地址已经到达２０个
    def create(self,request,*args,**kwargs):
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >=21:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        return super(AddressesView,self).create(request,*args,**kwargs)

    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        request.user.default_address_id = pk
        request.user.save()
        return Response(status=status.HTTP_200_OK)

    @action(methods=['put'],detail=True)
    def title(self,request,pk):
        dict_data = request.data

        address = self.get_object()

        serializer = serializers.AddressTitleSerializer(instance=address,data=dict_data)

        serializer.is_valid()

        serializer.save()

        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True

        instance.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

class UserBrowerHistoryView(CreateAPIView):
    serializer_class = serializers.UserBrowerHistorySerializer

    def get(self, request):
        # 1,获取redis中的数据
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s" % request.user.id, 0, 4)

        # 2,拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "default_image_url": sku.default_image_url,
                "name": sku.name,
                "price": sku.price,
                "comments": sku.comments,
                "id": sku.id
            }
            sku_list.append(sku_dict)

        # 3,返回
        return Response(sku_list)

class UserObtainJSONWebToken(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        # 1,调用父类方法
        response = super().post(request, *args, **kwargs)

        # 2,获取序列化器
        serializer = self.get_serializer(data=request.data)

        # 3,判断是否认证成功
        if serializer.is_valid():
            # 3.1获取user对象
            user = serializer.validated_data.get("user")

            # 3.2合并购物车
            # response = merge_cookie_redis_cart(request,user,response)

        return response